<template>
  <div class="login-container">
    <!-- 标签页切换（登录/注册） -->
    <div class="tab-group">
      <button 
        class="tab-btn" 
        :class="{ active: isLogin }" 
        @click="isLogin = true"
      >
        登录
      </button>
      <button 
        class="tab-btn" 
        :class="{ active: !isLogin }" 
        @click="isLogin = false"
      >
        注册
      </button>
    </div>

    <form @submit.prevent="handleSubmit" class="form">
      <!-- 账号输入（根据登录方式切换） -->
      <div class="form-group">
        <label :for="authType === 'tel' ? 'tel' : authType === 'email' ? 'email' : 'id'">
          {{ authType === 'tel' ? '手机号' : authType === 'email' ? '邮箱' : '账号' }}
        </label>
        <input
          :type="authType === 'email' ? 'email' : 'text'"
          :id="authType === 'tel' ? 'tel' : authType === 'email' ? 'email' : 'id'"
          v-model="formData[authType]"
          :placeholder="`请输入${prompt}`"
          required
        >
      </div>

      <!-- 邮箱输入（仅注册显示） -->
      <div class="form-group" v-if="!isLogin">
        <label for="regEmail">邮箱</label>
        <input
          type="email"
          id="regEmail"
          v-model="formData.email"
          placeholder="请输入邮箱"
          required
        >
      </div>

      <!-- 密码输入 -->
      <div class="form-group">
        <label for="password">密码</label>
        <div class="password-input">
          <input
            :type="showPassword ? 'text' : 'password'"
            id="password"
            v-model="formData.password"
            placeholder="请输入密码"
            required
          >
          <button
            type="button"
            class="toggle-password"
            @click="showPassword = !showPassword"
          >
            {{ showPassword ? '隐藏' : '显示' }}
          </button>
        </div>
      </div>

      <!-- 确认密码（仅注册显示） -->
      <div class="form-group" v-if="!isLogin">
        <label for="confirmPassword">确认密码</label>
        <input
          :type="showPassword ? 'text' : 'password'"
          id="confirmPassword"
          v-model="formData.confirmPassword"
          placeholder="请再次输入密码"
          required
        >
      </div>
	  <!-- 登录/注册方式选择 -->
      <div class="auth-method" v-if=isLogin>
        <label class="method-option">
          <input type="radio" v-model="authType" value="tel" checked />
          手机号登录
        </label>
        <label class="method-option">
          <input type="radio" v-model="authType" value="email" />
          邮箱登录
        </label>
        <label class="method-option">
          <input type="radio" v-model="authType" value="id" />
          账号登录
        </label>
      </div>
	  
      <!-- 提交按钮 -->
      <button type="submit" class="submit-btn">
        {{ isLogin ? '登录' : '注册' }}
      </button>
    </form>
  </div>
</template>

<script>
import router from '../router/index';
import { Signin } from '../utils/dataControler';
import { Login } from '../utils/dataControler';

export default {
  emits: ['login-success'],
  data() {
    return {
      isLogin: true,
      showPassword: false,
      authType: 'tel', // 默认为手机号登录
      formData: {
        tel: '',
        email: '',
        id: '',
        password: '',
        confirmPassword: ''
      }
    }
  },
  computed: {
    prompt() {
      return this.authType === 'tel' ? '手机号' : this.authType === 'email' ? '邮箱' : '账号';
    }
  },
  watch: {
    // 监听登录/注册切换：清空所有输入 + 重置为手机号登录
    isLogin() {
      this.authType = 'tel';
      this.resetAllFields();
    },
    // 监听登录方式切换：清空对应输入栏
    authType() {
      this.formData[this.authType] = '';
    }
  },
  methods: {
    // 清空所有输入字段
	resetAllFields() {
	  this.formData = {
		tel: '',
		email: '',
		id: '',
		password: '',
		confirmPassword: ''
	  };
	},
    // 表单验证
    validateForm() {
      let isValid = true;
      const { tel, email, id, password, confirmPassword } = this.formData;
      
      // 验证账号
      if (this.authType === 'tel') {
        const telReg = /^1[3-9]\d{9}$/;
        if (!tel) {
          alert('手机号不能为空');
          isValid = false;
        } else if (!telReg.test(tel)) {
          alert('请输入有效的手机号');
          isValid = false;
        }
      } else if (this.authType === 'email') {
        const emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!email) {
          alert('邮箱不能为空');
          isValid = false;
        } else if (!emailReg.test(email)) {
          alert('请输入有效的邮箱地址');
          isValid = false;
        }
      } else {
        if (!id) {
          alert('账号不能为空');
          isValid = false;
        } else if (id.length < 4) {
          alert('账号至少4个字符');
          isValid = false;
        }
      }

      // 验证密码
      if (!password) {
        alert('密码不能为空');
        isValid = false;
      } else if (password.length < 6) {
        alert('密码至少6个字符');
        isValid = false;
      }

      // 注册模式下验证确认密码
      if (!this.isLogin && password !== confirmPassword) {
        alert('两次输入的密码不一致');
        isValid = false;
      }

      return isValid;
    },

    // 处理表单提交
    async handleSubmit() {
      if (this.validateForm()) {
        try {
          if (this.isLogin) {
			let info = this.authType === 'tel' ? this.formData.tel : this.authType === 'email' ? this.formData.email : this.formData.id;
            // response = Login(this.authType, info, this.formData.password);
			// if(response){
			//   await new Promise(resolve => setTimeout(resolve, 800));
			//   router.push("/mainView");
			// }
			// else{
			//   error = response.error;
			//   alert("登录失败");
			// }
          } else {
            // response = Signin(this.formData.tel, this.formData.email, this.formData.password);
			// if(response){
				
			//   await new Promise(resolve => setTimeout(resolve, 800));
			//   alert('注册成功，请登录');
			//   this.isLogin = true;
			// }
			// else{
			// 	error = response.error;
			// 	alert("注册失败");
			// }
			this.isLogin = true;
            console.log('注册数据:', {
              tel: this.formData.tel,
              email: this.formData.email,
              password: this.formData.password
            });
          }
		  router.push("/mainView");
        } catch (error) {
          console.error('请求失败:', error);
          alert('操作失败，请稍后重试');
        }
      }
    }
  }
}
</script>

<style scoped>
.login-container {
  min-width: 400px;
  margin: 50px auto;
  padding: 20px;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.auth-method {
  display: flex;
  margin-bottom: 20px;
  gap: 15px;
}

.method-option {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.method-option input {
  margin-right: 5px;
}

.tab-group {
  display: flex;
  margin-bottom: 20px;
}

.tab-btn {
  flex: 1;
  padding: 10px;
  border: none;
  border-bottom: 2px solid #eee;
  background-color: transparent;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.tab-btn.active {
  border-bottom-color: #3498db;
  color: #3498db;
  font-weight: 600;
}

.form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group label {
  margin-bottom: 5px;
  font-weight: 500;
}

.form-group input {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.password-input {
  display: flex;
  align-items: center;
}

.password-input input {
  flex: 1;
}

.toggle-password {
  padding: 10px;
  border: none;
  border-radius: 4px;
  background-color: #f5f5f5;
  cursor: pointer;
}
.toggle-password:hover{
  background-color: #eee;
}

.submit-btn {
  padding: 12px;
  border: none;
  border-radius: 4px;
  background-color: #3498db;
  color: #fff;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.submit-btn:hover {
  background-color: #2980b9;
}
</style>